package org.example.netty.springBoot;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Netty 服务端处理器
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2021/8/9 14:53
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(NettyServerHandler.class);

    /**
     * 客户端连接成功后，自动触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("有客户端【{}】连接成功！", ctx.name());
    }

    /**
     * 收到客户端消息后自动触发
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("收到客户端【{}】消息: {}", ctx.name(), msg.toString());
        ctx.write("收到 【" + msg + "】");
        ctx.flush();
    }

    /**
     * 发生异常触发
     * 关闭 ChannelHandlerContext，释放和它相关联的句柄等资源
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}